package com.gomoku.backend.service.impl.user;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gomoku.backend.mapper.RecordMapper;
import com.gomoku.backend.mapper.UserMapper;
import com.gomoku.backend.pojo.Record;
import com.gomoku.backend.pojo.User;
import com.gomoku.backend.service.user.UserContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserContentServiceImpl implements UserContentService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Override
    public JSONObject getUserRecords(Integer userId, Integer page) {
        System.out.println(userId+" "+page);
        IPage<Record> iPage = new Page<>(page,5); //每页的条目数应该是后端传过去的
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        //找一下 数据库中表record 中 字段a_id b_id  == userId 的条目
        queryWrapper.eq("a_id", userId)
                .or()
                .eq("b_id", userId)
                .orderByDesc("id"); // 假设id递增，倒序即最新记录在前

        // 4. 执行分页查询
        IPage<Record> resultPage = recordMapper.selectPage(iPage, queryWrapper);
        List<Record> records = resultPage.getRecords();

        JSONObject resp = new JSONObject();
        List<JSONObject> items = new ArrayList<>();
        for (Record record : records) {
            User userA = userMapper.selectById(record.getAId());
            User userB = userMapper.selectById(record.getBId());
            JSONObject item = new JSONObject();
            item.put("a_username", userA.getUsername());
            item.put("a_photo", userA.getPhoto());
            item.put("b_username", userB.getUsername());
            item.put("b_photo", userB.getPhoto());
            String result = "平局";
            //这里判断输赢是看id来的如果我们是 a_id ==userId && A 胜
            if(userId.equals(record.getAId()) && "A".equals(record.getLoser())){
                result = "你赢了";
            }else if(userId.equals(record.getBId()) && "B".equals(record.getLoser())){
                result = "你赢了";
            }else {
                result = "你输了";
            }
            item.put("result", result);
            item.put("record", record);
            items.add(item);
        }
        resp.put("records", items);//并不是传一个json列表,而是传递封装好的一个json
        resp.put("records_count", resultPage.getTotal());
        System.out.println(resp);
        return resp;
    }
}
